<template>
    <div>
        <div
            v-if="store.deviceType !== 'mobile'"
            class="nav"
            :class="{ 'nav-blur': isScrolled, 'nav-white': isWhiteTheme }">
            <div class="nav-body">
                <div class="logo-content">
                    <img :src="logo" />
                </div>
                <div class="nav-right">
                    <div class="menus">
                        <div
                            v-for="(item, index) in menusData"
                            :key="item.label"
                            class="item"
                            :class="[isMenuActive(item.key) && 'active']"
                            @click="handleNav(index)">
                            <span>
                                {{ item.label }}
                            </span>

                            <div
                                v-if="item.submenu?.length"
                                class="submenu-menus">
                                <div
                                    v-for="(sItem, sIndex) in item.submenu"
                                    :key="sIndex"
                                    class="sub-item"
                                    @click="handleSubMenuClick(item, sItem)">
                                    {{ sItem.label }}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="btn"><nuxt-link to="#contact">Contact Us</nuxt-link></div>
                </div>
            </div>
        </div>
        <div
            v-if="store.deviceType === 'mobile'"
            class="nav"
            :class="{ 'nav-blur': isScrolled, 'nav-white': isWhiteTheme }">
            <div class="logo-content">
                <img :src="logo" />
            </div>
            <div
                ref="mMenusDetailRef"
                class="right-menus-more"
                @click="handlechangeShowMenu">
                <img src="/newHome/icon-nav-more.png" />
            </div>
        </div>
        <div
            v-if="store.deviceType === 'mobile'"
            :class="[isShowMMenus && 'active']"
            class="m-menus-detail">
            <div
                v-for="(item, index) in menusData"
                :key="item.label"
                class="m-menu-item"
                :class="[isMenuActive(item.key) && 'active']">
                <div
                    class="m-menu-main"
                    @click="handleNav(index, $event)">
                    <span>{{ item.label }}</span>
                    <div
                        v-if="item.submenu?.length"
                        class="m-menu-arrow"
                        :class="[isMobileMenuExpanded(item.key) && 'expanded']">
                        <img src="/newHome/icon-left-arrow.png" />
                    </div>
                </div>
                <div
                    v-if="item.submenu?.length"
                    class="m-submenu"
                    :class="[isMobileMenuExpanded(item.key) && 'expanded']">
                    <div
                        v-for="(subItem, subIndex) in item.submenu"
                        :key="subIndex"
                        class="m-submenu-item"
                        @click="handleSubMenuClick(item, subItem, $event)">
                        {{ subItem.label }}
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
    import {
        watch,
        isRef,
        unref,
        onUnmounted,
        onDeactivated,
        type WatchStopHandle,
        onActivated,
    } from 'vue';

    const router = useRouter();
    const route = useRoute();

    const WhiteRouteName = ['technology-ecology', 'risk-compliance'];

    const menusData = ref([
        {
            key: 'index',
            label: 'Home',
            url: '/',
            submenu: [
                {
                    label: 'About FAWA',
                    id: '#about-fawa',
                },
                {
                    label: 'Vision',
                    id: '#our-vision',
                },
                {
                    label: 'Mission',
                    id: '#mission',
                },
                {
                    label: 'Core Value',
                    id: '#platform-core-value',
                },
                {
                    label: 'Global development goals',
                    id: '#global-development-goals',
                },
                {
                    label: 'Digital Potential of Muslim Women',
                    id: '#digital',
                },
                {
                    label: `FAWA's Starting Point`,
                    id: '#the-beginning-of-fawa',
                },
                {
                    label: 'Business Model and Value Creation',
                    id: '#business-model',
                },
                {
                    label: 'Global Strategic Blueprint',
                    id: '#strategic-blueprint',
                },
            ],
        },
        {
            key: 'technology-ecology',
            label: 'Ecology and Technology',
            url: '/technology/ecology',
            submenu: [
                {
                    label: `FAWA's DAO Governance Framework`,
                    id: '#frameworkId',
                },
                {
                    label: `The Value of Community Autonomy`,
                    id: '#autonomyId',
                },
                {
                    label: `FAWA's Decentralized Social Design`,
                    id: '#decentralizedId',
                },
                {
                    label: `Strategic Value`,
                    id: '#strategicValueId',
                },
                {
                    label: `FAWA's Depin Infrastructure Design`,
                    id: '#infrastructureId',
                },
                {
                    label: `Strategic Value`,
                    id: '#strategicId',
                },
            ]
        },
        {
            key: 'token-fawa',
            label: 'Token',
            url: '/token/fawa',
            submenu: [
                {
                    label: 'Token Basic Information and Positioning',
                    id: '#basicInfoSectionId',
                },
                {
                    label: 'Functional Positioning',
                    id: '#functionalPositioningId',
                },
                {
                    label: 'Strategic Value',
                    id: '#strategicValueId',
                },
                {
                    label: 'Allocation Structure and Ratio Design',
                    id: '#allocationStructureId',
                },
                {
                    label: 'Allocation Design Logic',
                    id: '#allocationDesignId',
                },
                {
                    label: 'Functions and Application Scenarios',
                    id: '#applicationScenariosId',
                },
            ]
        },
        {
            key: 'system-compliance',
            label: 'Compliance system',
            url: '/system/compliance',
            submenu: [
                {
                    label: 'Foundation and DAO Dual-Layer Structure',
                    id: '#daoBox',
                },
                {
                    label: 'International Compliance System',
                    id: '#systemBox',
                },
                {
                    label: 'Regional Compliance Layout',
                    id: '#regionalBox',
                },
                {
                    label: 'Legal Audit and Intellectual Property Protection',
                    id: '#legalBox',
                },
            ],
        },
        {
            key: 'risk-compliance',
            label: 'Risk and Compliance',
            url: '/risk/compliance',
            submenu: [
                {
                    label: 'Market and Liquidity Risk',
                    id: '#marketBox',
                },
                {
                    label: 'Policy and Regulatory Risk',
                    id: '#policyBox',
                },
                {
                    label: 'Technology and Security Risk',
                    id: '#technicalBox',
                },
                {
                    label: 'Risk Control Logic',
                    id: '#logicBox',
                },
                {
                    label: 'Professional Conclusion',
                    id: '#professionalBox',
                },
            ],
        },
    ]);

    const isShowMMenus = computed(() => store.isShowMMenus);

    // 移动端子菜单展开状态管理
    const expandedMenus = ref<Set<string>>(new Set());

    // 根据当前路由名称计算激活的菜单项
    const getActiveKey = computed(() => {
        return (route.name as string) || 'index';
    });

    // 判断菜单项是否激活
    const isMenuActive = (menuKey: string) => {
        return getActiveKey.value === menuKey;
    };

    const isWhiteTheme = computed(() => {
        return WhiteRouteName.includes(route.name);
    });

    const logo = computed(() => {
        if (isWhiteTheme.value) return `/newHome/logo-white.png`;
        else return `/newHome/logo.png`;
    });

    // 添加滚动状态响应式变量
    const isScrolled = ref(false);

    import { useGlobalStore } from '~/store';

    const store = useGlobalStore();

    // 确保在组件初始化时就设置设备类型，避免SSR hydration问题
    if (process.client) {
        if (window.screen.width <= 768 || window.innerWidth <= 768) {
            store.deviceType = 'mobile';
        } else {
            store.deviceType = 'pc';
        }
    }

    const handlechangeShowMenu = () => {
        store.isShowMMenus = !isShowMMenus.value;
        // 关闭菜单时重置所有展开状态
        if (!store.isShowMMenus) {
            expandedMenus.value.clear();
        }
    };

    const handleNav = (num: number, event?: Event) => {
        const mItem = menusData.value[num];

        // 如果有子菜单且在移动端，则展开/收起子菜单
        if (mItem.submenu?.length && store.deviceType === 'mobile') {
            // 阻止事件冒泡，避免关闭整个菜单
            if (event) {
                event.stopPropagation();
            }
            toggleMobileSubmenu(mItem.key);
        } else {
            // 没有子菜单或在PC端，直接跳转
            store.isShowMMenus = false;
            router.push(mItem.url);
        }
    };

    // 切换移动端子菜单展开状态
    const toggleMobileSubmenu = (menuKey: string) => {
        const newExpandedMenus = new Set(expandedMenus.value);
        if (newExpandedMenus.has(menuKey)) {
            newExpandedMenus.delete(menuKey);
        } else {
            newExpandedMenus.add(menuKey);
        }
        expandedMenus.value = newExpandedMenus;
    };

    // 检查移动端菜单是否展开
    const isMobileMenuExpanded = (menuKey: string) => {
        return expandedMenus.value.has(menuKey);
    };

    // 处理子菜单项点击
    const handleSubMenuClick = (parentItem: any, subItem: any, event?: Event) => {
        // 阻止事件冒泡
        if (event) {
            event.stopPropagation();
        }

        // 关闭移动端菜单并重置展开状态
        store.isShowMMenus = false;
        expandedMenus.value.clear();

        // 如果当前已经在目标页面，直接滚动到元素
        if (route.path === parentItem.url) {
            scrollToElement(subItem.id);
        } else {
            // 存储目标hash到sessionStorage，供目标页面使用
            if (process.client) {
                sessionStorage.setItem('scrollToHash', subItem.id);
            }

            // 先跳转到页面，不带hash
            router.push(parentItem.url);
        }
    };

    // 滚动到指定元素的函数，带重试机制
    const scrollToElement = (elementId: string, maxRetries = 10, delay = 100) => {
        const element = document.querySelector(elementId);
        if (element) {
            element.scrollIntoView({ behavior: 'smooth', block: 'start' });
        } else if (maxRetries > 0) {
            // 如果元素还没加载，等待一段时间后重试
            setTimeout(() => {
                scrollToElement(elementId, maxRetries - 1, delay);
            }, delay);
        }
    };

    // 滚动处理函数
    const handleScroll = () => {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        isScrolled.value = scrollTop > 50; // 滚动超过50px时显示模糊背景
    };

    onMounted(() => {
        const store = useGlobalStore();

        // 确保移动端菜单在页面加载时是关闭的，并重置展开状态
        store.isShowMMenus = false;
        expandedMenus.value.clear();

        if (window.screen.width <= 768 || window.innerWidth <= 768) {
            store.deviceType = 'mobile';
        } else {
            store.deviceType = 'pc';
        }
        console.info('store.deviceType', store.deviceType);

        window.addEventListener('resize', (e: Event) => {
            const target = e.target as any;
            if (target.screen.width <= 768 || target.innerWidth <= 768) {
                store.deviceType = 'mobile';
            } else {
                store.deviceType = 'pc';
            }
        });

        // 添加滚动监听器
        window.addEventListener('scroll', handleScroll, { passive: true });

        // 页面加载完成后，处理滚动定位
        nextTick(() => {
            // 优先检查sessionStorage中的hash（来自跨页面跳转）
            const storedHash = sessionStorage.getItem('scrollToHash');
            if (storedHash) {
                sessionStorage.removeItem('scrollToHash'); // 清除已使用的hash
                setTimeout(() => {
                    scrollToElement(storedHash, 30, 150);
                }, 800); // 给页面更多时间加载
            } else if (route.hash) {
                // 处理URL中的hash
                setTimeout(() => {
                    scrollToElement(route.hash, 20, 200);
                }, 500);
            }
        });

        // console.info('mMenusDetailRef', mMenusDetailRef.value);
    });

    // 监听路由变化，处理hash定位
    watch(
        () => route.path,
        () => {
            nextTick(() => {
                // 检查是否有待定位的hash
                const storedHash = sessionStorage.getItem('scrollToHash');
                if (storedHash) {
                    sessionStorage.removeItem('scrollToHash');
                    setTimeout(() => {
                        scrollToElement(storedHash, 25, 200);
                    }, 600);
                } else if (route.hash) {
                    setTimeout(() => {
                        scrollToElement(route.hash, 15, 200);
                    }, 300);
                }
            });
        }
    );

    // 组件卸载时清理滚动监听器
    onUnmounted(() => {
        window.removeEventListener('scroll', handleScroll);
    });

    const onMountedOrActivated = (hook: () => any) => {
        let mounted: boolean;

        onMounted(() => {
            hook();
            nextTick(() => {
                mounted = true;
            });
        });

        onActivated(() => {
            if (mounted) {
                hook();
            }
        });
    };
    const useEventListener = (type: any, listener: any, options: any = {}) => {
        // if (process.server) return;

        console.info('useEventListener...');

        const { target = window, passive = false, capture = false } = options;

        let cleaned = false;
        let attached: boolean;

        const add = (target?: any) => {
            if (cleaned) {
                return;
            }
            const element = unref(target);

            if (element && !attached) {
                console.info('add...');
                element.addEventListener(type, listener, {
                    capture,
                    passive,
                });
                attached = true;
            }
        };

        const remove = (target?: any) => {
            if (cleaned) {
                return;
            }
            const element = unref(target);

            if (element && attached) {
                element.removeEventListener(type, listener, capture);
                attached = false;
            }
        };

        onUnmounted(() => remove(target));
        onDeactivated(() => remove(target));
        onMountedOrActivated(() => add(target));

        let stopWatch: WatchStopHandle;

        if (isRef(target)) {
            stopWatch = watch(target, (val, oldVal) => {
                remove(oldVal);
                add(val);
            });
        }

        /**
         * Clean up the event listener
         */
        return () => {
            console.info('useEventListener...');
            stopWatch?.();
            remove(target);
            cleaned = true;
        };
    };
    const useClickAway = (target: any, listener: any, options: any = {}) => {
        // if (process.server) return;

        const { eventName = 'click' } = options;

        console.info('useClickAway', eventName, target);

        const onClick = (event: Event) => {
            const targets = Array.isArray(target) ? target : [target];
            const isClickAway = targets.every(item => {
                const element = unref(item);
                return element && !element.contains(event.target as Node);
            });

            if (isClickAway) {
                listener(event);
            }
        };

        useEventListener(eventName, onClick, { target: document });
    };

    const mMenusDetailRef = ref();

    useClickAway(mMenusDetailRef, () => {
        console.info('click outside!', mMenusDetailRef.value);
        try {
            // isShowMMenus.value = false;
            store.isShowMMenus = false;
        } catch (e) {
            console.error(e);
        }
    });
</script>

<style lang="scss" scoped>
    // 导入响应式 mixins
    @use '@/styles/mixins/responsive' as *;

    .nav {
        // width: pxToRem(1920);
        width: 100%;
        height: pxToRem(88);
        left: 0;
        // margin-left: pxToRem(-960);
        background: transparent;
        display: flex;
        justify-content: center;
        top: 0;
        position: fixed;
        align-items: center;
        z-index: 1000;
        color: #00000066;
        font-size: pxToRem(16);
        font-weight: 400;
        line-height: pxToRem(20);
        transition: all 0.3s ease;
        .nav-body {
            width: 100%;
            max-width: pxToRem(1300);
            padding: 0 pxToRem(30);
            box-sizing: border-box;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: space-between;
        }

        // 滚动时的模糊背景效果
        &.nav-blur {
            background: rgba(255, 255, 255, 0.3);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        // 白色导航样式
        &.nav-white {
            color: #fff;

            .menus .item span {
                color: #fff;
            }

            .menus .item.active span {
                color: #fff;
            }

            .btn a {
                color: #fff;
            }

            // 白色主题时的模糊背景效果
            &.nav-blur {
                background: rgba(0, 0, 0, 0.3);
                backdrop-filter: blur(20px);
                -webkit-backdrop-filter: blur(20px);
                border-bottom: 1px solid rgba(0, 0, 0, 0.1);
            }
        }
        .logo-content {
            // width: pxToRem(454);
            height: pxToRem(48);
            display: flex;
            align-items: center;
            img {
                width: pxToRem(130);
                height: pxToRem(36);
                object-fit: contain;
            }
        }
        .nav-right {
            flex: 1;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: flex-end;
        }
        .menus {
            display: flex;
            margin-left: pxToRem(40);
            .item {
                position: relative;
                margin-right: pxToRem(40);
                height: pxToRem(36);
                display: flex;
                align-items: center;
                cursor: pointer;
                span {
                    font-family: 'Montserrat', sans-serif;
                    color: #00000066;
                    text-decoration: none;
                    white-space: nowrap;
                    display: flex;
                    align-items: center;
                    width: 100%;
                    height: 100%;
                    cursor: pointer;
                }
                &.active {
                    color: #000000e5;
                    font-weight: bold;
                    position: relative;
                    // @extend .custom-font-bold;
                    &::after {
                        content: '';
                        width: pxToRem(46);
                        height: pxToRem(4);
                        border-radius: pxToRem(2);
                        // background: #e27049;
                        background: linear-gradient(84.82deg, #fd2aa5 0%, #fb7771 95.69%);

                        position: absolute;
                        left: 50%;
                        margin-left: pxToRem(-23);
                        bottom: pxToRem(-6);
                    }
                    span {
                        color: #000000e5;
                    }
                }

                // 默认隐藏子菜单
                .submenu-menus {
                    position: absolute;
                    top: 100%;
                    left: 50%;
                    transform: translateX(-50%);
                    background: rgba($color: #f7f7f7, $alpha: 0.96);
                    backdrop-filter: blur(20px);
                    -webkit-backdrop-filter: blur(20px);
                    border: pxToRem(1) solid #ffffff;
                    border-radius: pxToRem(8);
                    padding: pxToRem(20) pxToRem(10);
                    box-sizing: border-box;
                    z-index: 10;
                    margin-top: pxToRem(25);
                    opacity: 0;
                    visibility: hidden;
                    transform: translateX(-50%) translateY(-10px);
                    transition: all 0.3s ease;

                    // 添加一个伪元素来填补间隙，方便鼠标移动
                    &::before {
                        content: '';
                        position: absolute;
                        top: pxToRem(-25);
                        left: 0;
                        right: 0;
                        height: pxToRem(25);
                        background: transparent;
                    }

                    .sub-item {
                        padding: pxToRem(18) pxToRem(16);
                        cursor: pointer;
                        font-size: pxToRem(14);
                        color: rgba($color: #000000, $alpha: 0.6);
                        border-radius: pxToRem(4);
                        white-space: nowrap;
                        transition: all 0.2s ease;
                        user-select: none;

                        &:hover {
                            // background-color: #f5f5f5;
                            color: rgba($color: #000000, $alpha: 0.9);
                            transform: translateX(2px);
                        }

                        &:active {
                            // background-color: #e5e5e5;
                            transform: translateX(1px);
                        }
                    }
                }

                // 悬停时显示子菜单
                &:hover .submenu-menus {
                    opacity: 1;
                    visibility: visible;
                    transform: translateX(-50%) translateY(0);
                }
            }
        }
        .btn {
            flex: 0 0 pxToRem(117);
            width: pxToRem(117);
            height: pxToRem(36);
            // background: #e27049;
            background: linear-gradient(84.82deg, #fd2aa5 0%, #fb7771 95.69%);

            color: #fff;
            border-radius: pxToRem(63);
            font-size: pxToRem(16);
            font-weight: 400;
            line-height: pxToRem(16);
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            a {
                color: #fff;
                text-decoration: none;
            }
        }
    }

    @include desktop-small {
        .nav {
            .menus {
                .item {
                    margin-right: pxToRem(20);
                }
            }
        }
    }

    // 响应式设计 - 中等屏幕 (1024px及以下)
    @include tablet {
        .nav {
            font-size: pxToRem(14);
            .menus {
                .item {
                    margin-right: pxToRem(15);
                }
            }
            .btn {
                display: none;
            }
        }
    }

    // 响应式设计 - 平板端 (768px及以下)
    @include mobile {
        .nav {
            width: pxToRem75(750);
            height: pxToRem75(70);
            margin-left: 0;
            top: 0;
            right: 0;
            left: 0;
            justify-content: space-between;
            background: #fff;

            position: fixed !important;
            transition: all 0.3s ease;

            // 移动端滚动时的模糊背景效果
            &.nav-blur {
                background: rgba(255, 255, 255, 0.4);
                backdrop-filter: blur(20px);
                -webkit-backdrop-filter: blur(20px);
                border-bottom: none;
            }

            // 移动端白色导航样式
            &.nav-white {
                background: transparent;
                color: #fff;

                .logo-content img {
                    // filter: brightness(0) invert(1);
                }

                .right-menus-more img {
                    filter: brightness(0) invert(1);
                }

                // 移动端白色主题时的模糊背景效果
                &.nav-blur {
                    background: rgba(0, 0, 0, 0.3);
                    backdrop-filter: blur(20px);
                    -webkit-backdrop-filter: blur(20px);
                    border-bottom: none;
                }
            }
            .logo-content {
                width: pxToRem75(166.8);
                height: pxToRem75(70);
                padding-left: pxToRem75(50);
                img {
                    width: pxToRem75(166.8);
                    height: pxToRem75(40);
                }
            }
            .right-menus-more {
                padding-right: pxToRem75(50);
                display: flex;
                align-items: center;
                justify-content: center;
                img {
                    width: pxToRem75(26);
                    height: pxToRem75(24);
                }
            }
            // .menus {
            //     margin-left: 0;
            // }
        }
        .m-menus-detail {
            position: fixed;
            // width: pxToRem75(298);
            top: pxToRem75(70);
            right: pxToRem75(10);
            padding: pxToRem75(30) 0px;
            box-sizing: border-box;
            font-size: pxToRem75(28);
            line-height: pxToRem75(30);
            color: #fff;
            display: none;
            flex-direction: column;
            justify-content: flex-start;
            align-items: center;
            z-index: 2;
            background: #000000a1;
            backdrop-filter: blur(pxToRem75(32));
            border-radius: pxToRem75(20);
            opacity: 0;
            transition: opacity 0.3s;
            max-height: 80vh;
            overflow-y: auto;

            &.active {
                display: flex;
                opacity: 1;
            }

            .m-menu-item {
                width: 100%;
                margin-bottom: pxToRem75(15);

                &:last-child {
                    margin-bottom: 0;
                }

                .m-menu-main {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    padding: 0 pxToRem75(20);
                    cursor: pointer;

                    span {
                        color: #fff;
                        text-decoration: none;
                        font-weight: 500;
                        font-size: pxToRem75(18);
                        flex: 1;
                        text-align: center;
                    }

                    .m-menu-arrow {
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        transition: transform 0.3s ease;

                        img {
                            width: pxToRem75(20);
                            height: pxToRem75(20);
                            filter: brightness(0) invert(1);
                            transform: rotate(-90deg);
                        }

                        &.expanded {
                            transform: rotate(180deg);
                        }
                    }
                }

                .m-submenu {
                    max-height: 0;
                    overflow: hidden;
                    transition: max-height 0.3s ease, padding 0.3s ease;
                    background: rgba(255, 255, 255, 0.1);
                    // border-radius: pxToRem75(20);
                    margin-top: pxToRem75(15);

                    &.expanded {
                        max-height: pxToRem75(2000);
                        padding: pxToRem75(20) pxToRem75(10);
                    }

                    .m-submenu-item {
                        // padding: pxToRem75(6) pxToRem75(10);
                        color: #fff;
                        font-size: pxToRem75(18);
                        font-weight: 400;
                        cursor: pointer;
                        border-radius: pxToRem75(10);
                        margin-bottom: pxToRem75(20);
                        transition: all 0.2s ease;
                        text-align: center;

                        &:last-child {
                            margin-bottom: 0;
                        }

                        // 移动端只保留点击时的反馈效果
                        &:active {
                            background: rgba(255, 255, 255, 0.15);
                            transform: scale(0.98);
                        }

                        // 添加点击后的视觉反馈
                        &:focus {
                            outline: none;
                            background: rgba(255, 255, 255, 0.1);
                        }
                    }
                }

                &.active {
                    .m-menu-main span {
                        color: #ee788f;
                        font-weight: 600;
                    }
                }
            }
        }
    }
</style>
